package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册
     */
    @Override
    public void register(MemberRegisterVo memberRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelService.queryDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名和手机号是否唯一。由于方法无返回值，要让上面感知到，所以采用异常机制，向上面抛异常
        checkUniqueMobile(memberRegisterVo.getPhone());
        checkUniqueUsername(memberRegisterVo.getUsername());
        //设置用户名和密码
        memberEntity.setMobile(memberRegisterVo.getPhone());
        memberEntity.setUsername(memberRegisterVo.getUsername());
        // 密码要加密存储
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(bCryptPasswordEncoder.encode(memberRegisterVo.getPassword()));
        // 其他的默认信息
        memberEntity.setCity("成都");
        memberEntity.setCreateTime(new Date());
        memberEntity.setStatus(0);
        memberEntity.setNickname(memberRegisterVo.getUsername());
        memberEntity.setBirth(new Date());
        memberEntity.setEmail("xxx@gmail.com");
        memberEntity.setGender(1);
        memberEntity.setJob("JAVA");
        baseMapper.insert(memberEntity);
    }

    /**
     * 检验用户名是否唯一
     */
    @Override
    public void checkUniqueUsername(String username) throws UsernameExistException {
        if (this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username)) > 0) {
            throw new UsernameExistException();
        }
    }

    /**
     * 检验手机号是否唯一
     */
    @Override
    public void checkUniqueMobile(String phone) throws PhoneExistException {
        if (this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone)) > 0) {
            throw new PhoneExistException();
        }
    }

    /**
     * 登录,一般返回一个实体类，网站登录进去可能有你好xxx，欢迎登录，方便给前端展示
     */
    @SuppressWarnings("all")
    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        //拿到用户填写的用户名和密码
        String loginacct = memberLoginVo.getLoginacct();
        String password = memberLoginVo.getPassword();
        MemberEntity memberEntity = this.baseMapper.selectOne(
                new QueryWrapper<MemberEntity>()
                        .eq("mobile", loginacct)
                        .or()
                        .eq("username", loginacct));
        //根据用户名和手机号查询到之后，说明用户已经注册，对提交的密码进行验证
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 前面传一个明文密码 后面传一个编码后的密码
        boolean flag = bCryptPasswordEncoder.matches(memberLoginVo.getPassword(), memberEntity.getPassword());
        if (flag) { //如果匹配到了,返回用户，但是为了安全将密码设置空再返回
            memberEntity.setPassword(null);
            return memberEntity;
        }
        return null;
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {

        // 微博的uid
        String uid = socialUser.getUid();
        // 1.判断社交用户登录过系统
        MemberDao dao = this.baseMapper;
        MemberEntity entity = dao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        MemberEntity memberEntity = new MemberEntity();
        if (entity != null) {
            // 说明这个用户注册过, 修改它的资料
            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpiresIn(socialUser.getExpiresIn());
            // 更新，有可能AccessToken过期了，所以要设置最新的AccessToken，方便下次拿到这个用户的AccessToken继续来使用
            //因为令牌当前只在客户端拿着，客户端一关就没了，access_token就没人知道是多少了，之后在过期时间内其实是可以做一个
            //免登录的，但是access_token不知道的话就没办法调用那些api了。
            dao.updateById(memberEntity);
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpiresIn(socialUser.getExpiresIn());
            entity.setPassword(null);
            return entity;
        } else {
            // 2. 没有查到当前社交用户对应的记录 我们就需要注册一个
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token", socialUser.getAccessToken());
            map.put("uid", socialUser.getUid());
            try {
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                // 3. 查询当前社交用户账号信息(昵称、性别等)
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    // 这个JSON对象什么样的数据都可以直接获取
                    JSONObject jsonObject = JSON.parseObject(json);
                    memberEntity.setNickname(jsonObject.getString("name"));
                    memberEntity.setUsername(jsonObject.getString("name"));
                    memberEntity.setGender("m".equals(jsonObject.getString("gender")) ? 1 : 0);
                    memberEntity.setCity(jsonObject.getString("location"));
                    memberEntity.setJob("IT");
                    memberEntity.setEmail(jsonObject.getString("email"));
                }
            } catch (Exception e) {
                log.warn("社交登录时远程调用出错 [尝试修复]");
            }
            memberEntity.setStatus(0);
            memberEntity.setCreateTime(new Date());
            memberEntity.setBirth(new Date());
            memberEntity.setLevelId(1L);
            //防止下次还是这个用户登录，就不用注册了
            memberEntity.setSocialUid(socialUser.getUid());
            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpiresIn(socialUser.getExpiresIn());

            // 注册 -- 登录成功
            dao.insert(memberEntity);
            memberEntity.setPassword(null);
            return memberEntity;
        }
    }
}